#!/urs/bin/env/python
# coding=utf-8
# __author__=${胡胡}
# __time__=2020/4/20
import requests
import datetime
import time
import base64
import json
import os
import shutil
import urllib.request
import oss2
import uuid

from io import BytesIO
from urllib.request import urlopen
from PIL import Image
from Crypto.Cipher import AES
from django.shortcuts import redirect

from libs.utils.ajax import ajax_fail
from libs.utils.com_func import Struct
from django.contrib.auth import authenticate, login, get_user_model
User = get_user_model()

def auth(fuc):
    def wrapper(request, *args, **kwargs):
        request_method = request.META.get("REQUEST_METHOD")
        print(json.loads(request.body))
        if request_method == 'GET':
            skey = request.GET.get("open_id")
        elif request_method == 'POST':
            skey = json.loads(request.body).get("open_id")
            print(skey)
        else:
            pass
        if not skey:
            return ajax_fail(message='未登录，请登录！')
        return fuc(request, *args, **kwargs)
    return wrapper


def now():
    return int(time.time())


def like_num(like, userlike):
    if userlike[0].likes_bool == 0:
        userlike[0].likes_bool = 1
        like[0].likes_num = int(like[0].likes_num) + 1
        userlike[0].save()
        like[0].save()
        return 1
    elif userlike[0].likes_bool == 1:
        userlike[0].likes_bool = 0
        like[0].likes_num = int(like[0].likes_num) - 1
        userlike[0].save()
        like[0].save()
        return 0

def get_today_0():
    """获取当天零点的时间戳"""
    today = datetime.date.today()
    today_time = int(time.mktime(today.timetuple()))

    return today_time


def dedupe(items, key=None):
    """
    字典列表去重
    :param key:
    :return:
    """
    seen = set()
    for item in items:
        val = item if key is None else key(item)
        if val not in seen:
            yield item
            seen.add(val)

class WXBizDataCrypt:
    def __init__(self, appId, sessionKey):
        self.appId = appId
        self.sessionKey = sessionKey

    def decrypt(self, encryptedData, iv):
        # base64 decode
        sessionKey = base64.b64decode(self.sessionKey)
        encryptedData = base64.b64decode(encryptedData)
        iv = base64.b64decode(iv)

        cipher = AES.new(sessionKey, AES.MODE_CBC, iv)

        decrypted = json.loads(self._unpad(cipher.decrypt(encryptedData)))

        if decrypted['watermark']['appid'] != self.appId:
            raise Exception('Invalid Buffer')

        return decrypted

    def _unpad(self, s):
        return s[:-ord(s[len(s)-1:])]

# 天数
def get_days(year, month, day):
    day_of_Feb = 29 if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 else 28
    day_of_month = (31, day_of_Feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
    result = sum(day_of_month[:month - 1]) + day
    return result

#显示时间
def show_times(now_time, add_time):
    subtract_time = (now_time - add_time)
    if subtract_time.days >= 365:
        show_time = add_time.strftime("%Y-%m-%d")
    elif 1 <= subtract_time.days <= 365:
        if get_days(int(now_time.strftime("%Y")),int(now_time.strftime("%m")),int(now_time.strftime("%d"))) < get_days(int(add_time.strftime("%Y")),int(add_time.strftime("%m")),int(add_time.strftime("%d"))):
            show_time = add_time.strftime("%Y-%m-%d")
        else:
            show_time = add_time.strftime("%m-%d")
    else:
        days, seconds = subtract_time.days, subtract_time.seconds
        hours = days * 24 + seconds // 3600
        minutes = (seconds % 3600) // 60
        if 0 <= hours < 1:
            if 0 <= minutes <= 3:
                show_time = "刚刚"
            else:
                show_time = str(minutes) + "分钟前"
        else:
            if 1 <= hours <= int(now_time.hour):
                show_time = str(hours) + "小时前"
            else:
                show_time = "昨天 " + add_time.strftime("%H:%M")

    return show_time

# 下载图片
def down_load_image(img_url, logoImgUrlTemp):
    file_path = r'C:\Users\Administrator\Desktop\projects\search_web\cms\statics\images\upimage'
    file_name = logoImgUrlTemp
    try:
        # 是否有这个路径
        if not os.path.exists(file_path):
            # 创建路径
            os.makedirs(file_path)
            # 获得图片后缀
        file_suffix = os.path.splitext(img_url)[1]
        # 拼接图片名（包含路径）
        filename = '{}{}{}{}'.format(file_path, os.sep, file_name, file_suffix)
        # 下载图片，并保存到文件夹中
        urllib.request.urlretrieve(img_url, filename=filename)

    except IOError as e:
        print("IOError")
    except Exception as e:
        print("Exception")

# 删除文件夹下面的所有文件
def remove_image(del_path):
    class DeleteFiles(object):
        def __init__(self, pathDir):
            self.pathDir = pathDir
        def delete_files(self):
            os.chdir(self.pathDir)
            fileList = list(os.listdir())
            for file in fileList:
                if os.path.isfile(file):
                    os.remove(file)
                    # print("delete successfully")
                else:
                    shutil.rmtree(file)
    delete = DeleteFiles(del_path)
    delete.delete_files()

def del_file_all(del_file_list):
    try:
        for x in del_file_list:
            try:
                os.remove(x.get('last_cover_file'))
            except:
                print("文件正在使用")
            try:
                os.remove(x.get('last_main_file'))
            except:
                print("文件正在使用")
            print("文件删除完毕")
    except:
        print("文件不存在")

def del_file_one(del_file):
    try:
        os.remove(del_file)
        print("文件删除完毕")
    except(FileNotFoundError):
        print("文件不存在")

# 下载视频到本地
def down_search_video(video_url):
    r = requests.get(video_url)
    data = r.content
    video_path = os.getcwd() + '\\myadmin\\search_video\\' +\
                 video_url.split('.')[-2].lower().split('/')[-1] + '.' + \
                 video_url.split('.')[-1].lower()
    with open(video_path, 'wb') as f:
        f.write(data)
        f.close()
        print('下载成功')
    return video_url.split('.')[-2].lower().split('/')[-1] + '.' + video_url.split('.')[-1].lower()

# 下载视频到本地
def down_excel(excel_url):
    r = requests.get(excel_url)
    data = r.content
    excel_path = os.getcwd() + '\\excel\\' + \
                 excel_url.split('.')[-2].lower().split('/')[-1] + '.' + \
                 excel_url.split('.')[-1].lower()
    with open(excel_path, 'wb') as f:
        f.write(data)
        f.close()
        print('下载成功')
    return excel_path.split('.')[-2].lower().split('/')[-1] + '.' + excel_path.split('.')[-1].lower()


# 下载视频到ubuntu共享文件夹本地
def down_ubuntu_video(video_url):
    r = requests.get(video_url)
    data = r.content
    now = int(time.time())
    video_path = "Y:\search_video\\" + video_url.split('.')[-2].lower().split('/')[-1] + "_" + str(now) + '.' + video_url.split('.')[-1].lower()
    with open(video_path, 'wb') as f:
        f.write(data)
        f.close()
        print('下载成功')
    return "/media/turing/mountdata2/my_share/search_video/" + video_url.split('.')[-2].lower().split('/')[-1] + "_" + str(now) + '.' + video_url.split('.')[-1].lower()

# 以流的形式存储图片到excel
def Bytesio_image(image, worksheet,  excel_row, tag):
    image_data = BytesIO(urlopen(image).read())
    im = Image.open(image_data)
    print (im.size)
    # original_width, original_height = im.size
    # width = cell_height * original_width / original_height
    # print(width, cell_height,'=dsadsdf')
    # im.thumbnail((width, cell_height), Image.ANTIALIAS)
    im.thumbnail((170, 90), Image.ANTIALIAS)
    im_bytes = BytesIO()
    im.save(im_bytes, format='JPEG')
    worksheet.insert_image(excel_row, tag, "", {'image_data': im_bytes, 'x_offset':10, 'y_offset':8})
    # office.close()

# 上传图片/视频 到oss 并返回 下载链接
def upload_oss_file(filename, file_path):
    # 例：upload_oss_file(r"C:\Users\Administrator\Desktop\projects\search_web\cms\statics\images\myadmin\2.jpg")
    # C:\Users\Administrator\Desktop\projects\search_web\cms\statics\images\myadmin\2.jpg
    # file_path   py_video_search
    access_key_id = "LTAI4G67zEEeC47qSXu4nggj"
    access_key_secret = "YpwfsYXagDicAZcQUPPERCnwyPBzbG"
    oss_url = "http://oss-cn-beijing.aliyuncs.com"
    bucket_name = "anyangoss"  # 正式
    # 连接阿里云oss
    auth = oss2.Auth(access_key_id, access_key_secret)
    bucket = oss2.Bucket(auth, oss_url, bucket_name)
    # 切割文件名后缀
    try:
        key_type = filename.split('.')[-1]
    except:
        key_type = ''
    # 调用文件夹分类，获取分类结果

    current_file_path = file_path + '/' + str(uuid.uuid1()) + '.' + key_type  # 本地测试  上传到OSS的文件名,uuid生成，保证唯一性

    file_path1 = filename  # 本地文件名，需要有可读权限
    key = current_file_path
    filename = file_path1
    # 上传
    try:
        bucket.put_object_from_file(current_file_path, file_path1)

        Content_MD5 = bucket.put_object_from_file(current_file_path, file_path1).headers.get('Content-MD5')
        ret = True

    except Exception as e:
        ret = False
        Content_MD5 = ''
    if ret and Content_MD5:
        os.remove(filename)
    else:
        ret = False
        Content_MD5 = ''
    return ret, Content_MD5, current_file_path

def media_audio(image, file_path, file_type, uuid_name):
    basedir = os.path.join(os.path.abspath('./'), 'statics', 'file', file_path)
    # print(os.path.abspath('./'))   # 获取当前目录
    if not os.path.exists(os.path.join(basedir)):
        path_1 = os.makedirs(os.path.join(basedir))
    path_1 = os.path.join(basedir)
    with open(os.path.join(path_1, r'{}'.format(uuid_name) + '.{}'.format(file_type)), 'wb') as f:
        f.write(image)
        f.close()
    return path_1

def del_search_video(rootdir):
    filelist=[]
    filelist=os.listdir(rootdir)
    for f in filelist:
        filepath = os.path.join( rootdir, f )
        if os.path.isfile(filepath):
            os.remove(filepath)
        elif os.path.isdir(filepath):
            shutil.rmtree(filepath,True)

def get_iqiyi_video_list(IqiyiVideo_list, task_id, username):
    task_result = []
    detection_obj = Detection.objects.filter(id=task_id).last()
    num = 1
    for obj in IqiyiVideo_list:
        row = Struct()
        row.num = num
        row.keyword = detection_obj.keyword if detection_obj else ""
        row.user_name = username
        row.id = obj.get('id')
        row.title = obj.get('title')
        row.name = obj.get('name')
        row.html_url = obj.get('href')
        row.commmen = obj.get('commmen')
        row.give = obj.get('give')
        # row.add_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(obj.get("time"))))
        row.add_time = obj.get("time")
        task_result.append(row)
        num += 1
    return task_result



def get_dirsir_list(data_list, task_id, username):
    task_result = []
    detection_obj = Detection.objects.filter(id=task_id).last()
    num = 1
    for obj in data_list:
        row = Struct()
        row.num = num
        row.keyword = detection_obj.keyword if detection_obj else ""
        row.user_name = username
        row.id = obj.id  # 主id
        row.goods_id = obj.goods_id  # 商店id
        row.shop_id = obj.shop_id  # 店铺id
        row.source = obj.source  # 平台名称
        row.goods_name = obj.goods_name  # 商品标题信息
        row.goods_price = obj.goods_price  # 商品价格
        row.goods_sales = obj.goods_sales  # 商品销量
        row.pic_url = obj.pic_url  # 商品图片链接
        row.item_loc = obj.item_loc  # 商品所在地
        row.detail_url = obj.detail_url  # 商品详情页链接
        row.comment_count = obj.comment_count  # 累计评论人数
        row.comment_url = obj.comment_url  # 累计评论链接
        row.goods_brand = obj.goods_brand  # 店铺名称
        row.shop_link = obj.shop_link  # 店铺链接
        row.task_id = int(obj.task_id)  # 任务id
        row.add_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(obj.timestamp)))
        task_result.append(row)
        num += 1
    return task_result


def get_text_list(data_list, task_id, username):
    # 获取文字详情数据
    task_result = []
    detection_obj = Detection.objects.filter(id=task_id).last()
    num = 1
    for obj in data_list:
        row = Struct()
        row.num = num
        row.keyword = detection_obj.keyword if detection_obj else ""
        row.user_name = username
        row.id = obj.id                             # 主id
        row.title = obj.title                       # 文章标题
        row.comment = obj.comment                   # 文章评论数
        row.source = obj.source                     # 平台名称
        row.name = obj.name                         # 文章的发布人
        row.url = obj.url                           # 文章的url
        row.imgs = obj.imgs                         # 文章内包含的图片
        row.content = obj.content                   # 文章的内容
        row.video_flag = obj.video_flag             # 章内是否包含视频 0 不是 1 是
        row.video_read = obj.video_read             # 文章视频内的点击数量
        row.task_id = obj.task_id                   # 任务id
        row.add_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(obj.add_time))) if obj.add_time else ""
        task_result.append(row)
        num += 1
    return task_result


def get_audio_list(data_list, task_id, username):
    # 获取音频详情数据
    task_result = []
    detection_obj = Detection.objects.filter(id=task_id).last()
    num = 1
    for obj in data_list:
        row = Struct()
        row.num = num
        row.keyword = detection_obj.keyword if detection_obj else ""
        row.user_name = username
        row.id = obj.id                         # 主id
        row.page_url = obj.page_url             # 页面url
        row.source = obj.source                 # 平台名称
        row.time = obj.time                     # 发布时间
        row.comment = obj.comment               # 评论次数
        row.name = obj.name                     # 主播名称
        row.title = obj.title                   # 标题
        row.audio_url = obj.audio_url           # 音频链接
        row.task_id = obj.task_id               # 任务id
        row.add_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(obj.add_time))) if obj.add_time else ""
        task_result.append(row)
        num += 1
    return task_result

def DelRepeat(data,key):
  new_data = [] # 用于存储去重后的list
  values = []  # 用于存储当前已有的值
  for d in data:
    if d[key] not in values:
      new_data.append(d)
      values.append(d[key])
  return new_data

def processing_data(data_list, Mname):
    result_list = []
    user_ids =[x.get("user_id") for x in data_list]
    # user_list = User.objects.filter(id__in=user_ids).values("id", "rank")
    # first_user_ids = [x for x in user_list if x.get("rank") == 1]    # 一级督导ids
    # two_user_ids = [x for x in user_list if x.get("rank") == 2]      # 二级督导ids
    new_data_list = DelRepeat(data_list, Mname)
    for obj in new_data_list:
        result_dict = {}
        data_obj = [x for x in data_list if x.get("teacher_name") == obj.get("teacher_name")]
        id = 0
        teacher_name = ""
        department_name = ""
        arrange_id = 0
        user_id = 0
        first_gross_score = 0
        two_gross_score = 0
        gross_score = 0
        type = 0
        first_user_mun = 0
        two_user_mun = 0
        rank_first_list = []
        rank_two_list = []
        for new_obj in data_obj:
            id = new_obj.get('id')
            teacher_name = new_obj.get('teacher_name', '')
            department_name = new_obj.get('department_name', '')
            arrange_id = new_obj.get('arrange_id')
            user_id = new_obj.get('user_id')
            type = new_obj.get('type')
            userObj = User.objects.filter(id=user_id).last()
            if not userObj:
                continue
            is_rank = userObj.rank
            if is_rank == 1:
                first_user_mun += 1
                first_gross_score += new_obj.get('gross_score')
                rank_first_list.append(user_id)
            elif is_rank == 2:
                two_user_mun += 1
                two_gross_score += new_obj.get('gross_score')
                rank_two_list.append(user_id)
        first_user_mun = first_user_mun if first_user_mun else 1
        two_user_mun = two_user_mun if two_user_mun else 1
        if rank_first_list and rank_two_list:
            gross_score = (first_gross_score*0.65)/int(first_user_mun) + (two_gross_score*0.35)/int(two_user_mun)
        if rank_first_list and not rank_two_list:
            gross_score = first_gross_score/int(first_user_mun)
        if not rank_first_list and rank_two_list:
            gross_score = two_gross_score/int(two_user_mun)
        result_dict["id"] = id
        result_dict["teacher_name"] = teacher_name
        result_dict["department_name"] = department_name
        result_dict["arrange_id"] = arrange_id
        result_dict["type"] = type
        result_dict["user_id"] = user_id
        result_dict["gross_score"] = round(gross_score, 2)
        result_list.append(result_dict)
    result_list = list(sorted(result_list, key=lambda p: p.get("gross_score"), reverse=True))
    return result_list